package com.xukun.changgou.auth.service;

import com.alibaba.fastjson.JSON;
import com.xukun.changgou.auth.feign.sys.SysUserFeign;
import com.xukun.changgou.auth.model.BaseUserDetails;
import com.xukun.changgou.common.constants.CommonConstant;
import com.xukun.changgou.common.redis.RedisUtil;
import com.xukun.changgou.common.response.ResponseData;
import com.xukun.changgou.common.response.ResponseEnum;
import com.xukun.changgou.common.response.exception.BaseException;
import com.xukun.changgou.service.api.sys.enums.UserStatusEnum;
import com.xukun.changgou.service.api.sys.model.UserModel;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author xukun
 * @Date 2021-06-02 15:49
 * @Description
 */
public class BaseUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserFeign userFeign;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 具体的登录逻辑
     *
     * @param username 登录账号
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (ObjectUtils.isEmpty(username)) {
            throw new BaseException("账号不能为空");
        }
        ResponseData userData = userFeign.queryUserByCode(username);
        if (userData.getCode() == ResponseEnum.FAIL.getCode()) {
            throw new BaseException(userData.getMessage());
        } else {
            UserModel userModel = JSON.parseObject(JSON.toJSONString(userData.getData()), UserModel.class);
            if (ObjectUtils.isEmpty(userModel)) {
                throw new UsernameNotFoundException("用户不存在");
            }

            List<String> authorityList = getAuthorities(userModel.getId(), userModel.getCode());
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            if (ObjectUtils.isNotEmpty(authorityList)) {
                authorityList.forEach(authority -> authorities.add(new SimpleGrantedAuthority(authority)));
            }
            BaseUserDetails userDetails = new BaseUserDetails(userModel.getCode(), userModel.getPassword(), userModel.getStatus() == UserStatusEnum.getValue(UserStatusEnum.正常), authorities);
            return userDetails;
        }

    }

    /**
     * 获取权限列表
     *
     * @param userId   用户id
     * @param username 用户名
     * @return list 权限列表
     */
    private List<String> getAuthorities(Integer userId, String username) {
        //根据用户名取出redis中的权限数据
        List<String> authorities;
        if (redisUtil.hasKey(username + CommonConstant.REDIS_USER_AUTH_SUFFIX)) {
            //从redis中取出该username的权限数据
            String auth = redisUtil.get(username + CommonConstant.REDIS_USER_AUTH_SUFFIX);
            if (ObjectUtils.isNotEmpty(auth)) {
                authorities = JSON.parseArray(auth, String.class);
            } else {
                ResponseData<List<String>> responseData = userFeign.queryPermissionListByUser(userId);
                authorities = responseData.getData();
            }
        } else {
            ResponseData<List<String>> responseData = userFeign.queryPermissionListByUser(userId);
            authorities = responseData.getData();
        }
        return authorities;
    }
}
